package com.yanftch.json2ets.json2ets.views


import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonParseException
import com.google.gson.JsonParser
import javax.swing.*
import java.awt.*
import com.intellij.openapi.ui.DialogWrapper
import com.yanftch.json2ets.json2ets.generator.MessageDelegate
import com.yanftch.json2ets.json2ets.parser.typescript.ParseType
import java.util.*

class Json2TsDialog(fileName: String? = "", dialogTitle:String? = "Json2ets") : DialogWrapper(true) {
    val dialogSize = 600
    lateinit var formatJsonBtn: JButton
    lateinit var generateButton: JButton
    lateinit var rootObjectName: JTextField
    lateinit var editor: JsonEditor
    private var listener: OnGenerateClicked? = null

    // interface 选择
    private lateinit var interfaceRadio: JRadioButton
    private lateinit var jsDocRadio: JRadioButton
    private lateinit var typeRadio: JRadioButton
    private lateinit var classRadio: JRadioButton

    init {
        title = dialogTitle
        init()

        setFormatHandle()
        rootObjectName.text = fileName ?: ""
    }

    override fun createCenterPanel(): JComponent? {
        // 主面板
        val mainPanel = JPanel(BorderLayout())
        mainPanel.preferredSize = Dimension(dialogSize, dialogSize)

        // JSON 编辑器
        editor = JsonEditor.createEditorByClipboard()
        editor.apply {
            setOneLineMode(false)
        }
//        val textArea = JTextArea()
//        textArea.border = BorderFactory.createTitledBorder("editor: JsonEditor")
        mainPanel.add(JScrollPane(editor), BorderLayout.CENTER)

        // 底部面板
        val bottomPanel = JPanel(BorderLayout()) // 底部主面板，使用 BorderLayout 分区域

        // 单选按钮区域
        val radioButtonPanel = JPanel(FlowLayout(FlowLayout.LEFT, 10, 10)) // 左对齐，水平间距10
        typeRadio = JRadioButton("Type")
        interfaceRadio = JRadioButton("Interface")
        classRadio = JRadioButton("Class")
        jsDocRadio = JRadioButton("JsDoc")
        val buttonGroup = ButtonGroup()
        buttonGroup.add(typeRadio)
        buttonGroup.add(interfaceRadio)
        buttonGroup.add(classRadio)
        buttonGroup.add(jsDocRadio)

        // 添加单选按钮到面板
        radioButtonPanel.add(typeRadio)
        radioButtonPanel.add(interfaceRadio)
        radioButtonPanel.add(classRadio)
        radioButtonPanel.add(jsDocRadio)

        bottomPanel.add(radioButtonPanel, BorderLayout.NORTH)

        // Root name 标签和输入框区域
        val rootNamePanel = JPanel(FlowLayout(FlowLayout.LEFT, 10, 0))
        val rootNameLabel = JLabel("Root name:")
        rootObjectName = JTextField(15)

        rootNamePanel.add(rootNameLabel)
        rootNamePanel.add(rootObjectName)
        bottomPanel.add(rootNamePanel, BorderLayout.CENTER)

        // 格式化和生成按钮区域
        val actionButtonPanel = JPanel(FlowLayout(FlowLayout.RIGHT, 10, 0)) // 右对齐
        formatJsonBtn = JButton("Format Json")
        generateButton = JButton("Generate")
        actionButtonPanel.add(formatJsonBtn)
        actionButtonPanel.add(generateButton)

        bottomPanel.add(actionButtonPanel, BorderLayout.SOUTH)

        // 添加到底部区域
        mainPanel.add(bottomPanel, BorderLayout.SOUTH)


        return mainPanel
    }


    override fun createButtonsPanel(buttons: MutableList<out JButton>): JPanel {
        return JPanel()
    }


    // 递归排序 JsonElement 中的所有对象
    private fun sortJsonElement(jsonElement: JsonElement): Map<String, Any> {
        val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create() // 保留JSON中value为null的键值对
        val unsortedMap: Map<String, Any> = gson.fromJson<Map<String, Any>>(jsonElement, Map::class.java)

        // 创建一个 TreeMap，使其自动按键排序
        val sortedMap: MutableMap<String, Any> = TreeMap()

        // 遍历每个键值对，处理嵌套的 Map
        for ((key, value) in unsortedMap) {
            if (value is Map<*, *>) {
                // 递归排序嵌套的 JSON 对象
                sortedMap[key] = sortJsonElement(gson.toJsonTree(value))
            } else {
                sortedMap[key] = value
            }
        }
        return sortedMap
    }

    private fun setFormatHandle() {
        formatJsonBtn.addActionListener {
            val json = editor.text
            json.let {
                val jsonString = try {
                    val sort = false
                    if (sort) {
                        val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create() // 保留JSON中value为null的键值对
                        val jsonElement = gson.fromJson(json, JsonElement::class.java)
                        val sortedMap: Map<String, Any> = sortJsonElement(jsonElement)
                        gson.toJson(sortedMap)
                    } else {
                        val rootJsonElement = JsonParser.parseString(json)
                        val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create() // 保留JSON中value为null的键值对
                        gson.toJson(rootJsonElement)
                    }

                } catch (e: JsonParseException) {
                    MessageDelegate().catchException(e, null)
                }
//                val jsonString = try {
//                    val rootJsonElement = JsonParser.parseString(json)
//                    val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create() // 保留JSON中value为null的键值对
//                    gson.toJson(rootJsonElement)
//                } catch (e: JsonParseException) {
//                    MessageDelegate().catchException(e, null)
//                }
                editor.text = jsonString as String

//                if (json.startsWith("{")) {
//                    val jsonObject: JSONObject = JSONObject(json)
//                    val formatJson = jsonObject.toString(4)
//                    editor.text = formatJson
//                } else if (json.startsWith("[")) {
//                    val jsonArray: JSONArray = JSONArray(json)
//                    val formatJson = jsonArray.toString(4)
//                    editor.text = formatJson
//                }
            }
        }
    }

    fun setOnGenerateListener(listener:  OnGenerateClicked) {
        this.listener = listener
        interfaceRadio.isSelected = true
        val radioList = listOf(interfaceRadio, jsDocRadio, typeRadio, classRadio)
        radioList.forEach {
            it.addActionListener {
                radioList
                    .filter { btn -> btn.text != it!!.actionCommand }
                    .forEach { btn -> btn.isSelected = false }
            }
        }
        generateButton.addActionListener {
            val selectedRadio = radioList.find { it.isSelected }
            selectedRadio?.let {
                val parseType = when (selectedRadio.text) {
                    "JsDoc" -> ParseType.JsDoc
                    "Type" -> ParseType.TypeStruct
                    "Class" -> ParseType.TSClass
                    "Interface" -> ParseType.InterfaceStruct
                    else -> ParseType.InterfaceStruct
                }
                val rootName = if (rootObjectName.text != "") {
                    rootObjectName.text
                } else "RootObject"
                this.listener?.onClicked(
                    rootName,
                    editor.text,
                    parseType
                )
            }

        }
    }

    interface OnGenerateClicked {
        fun onClicked(rootName: String, json: String, parseType: ParseType)
    }
}

// 显示弹窗
//fun showJsonEditorDialog() {
//    val dialog = JsonEditorDialog()
//    dialog.show()
//}
//
//// 插件入口
//fun main() {
//    SwingUtilities.invokeLater {
//        showJsonEditorDialog()
//    }
//}

